package com.google.memoryofaplace;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.memoryofaplace.model.TBPlaceMedia;
import com.google.memoryofaplace.model.TBPlaces;

public class BLPlaceMedia {

	public static JSONObject addPlaceMedia(long codPlace, String url,
			String thumbnail, String title, String description, int mediaType,
			int contentType, Date taken, String user) throws JSONException {
		JSONObject jResult = new JSONObject();

		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			TBPlaces place = pm.getObjectById(TBPlaces.class,
					KeyFactory.createKey("TBPlaces", codPlace));
			if (place == null) {
				jResult = General.returnError("event " + codPlace
						+ " not found");
			} else {

				List<TBPlaceMedia> media = place.getMedia();
				if (media == null) {
					media = new ArrayList<TBPlaceMedia>();
				}
				TBPlaceMedia placeMedia = new TBPlaceMedia(url, thumbnail,
						title, description, mediaType, contentType, taken, user);
				media.add(placeMedia);
				pm.makePersistent(place);
				pm.close();
				jResult.put("status", General.OK);
				jResult.put("date", General.formatDate(new Date()));
				jResult.put("codplacemedia", placeMedia.getCodPlaceMedia());
			}
		} catch (Exception e) {
			jResult = new JSONObject();
			jResult = General.returnError(e.getMessage());
		}
		return jResult;
	}

}
